// 匿名函数
(async function() {
	let params = getJsParams('macro_onlyoffice_editor_ctl');
  console.log('params', params);
  let fieldName = params.fieldName;
  let formCode = params.formCode;
  let onlyofficeServerUrl = params.onlyofficeServerUrl; 
  let rootPath = params.rootPath;
  let ext = params.ext;
  let flowId = params.flowId;
  let attachId = params.attachId;
  let token = params.token;
  let formName = params.formName;
  let type = params.type;
  let id = params.attachId;
  let mode = params.mode;
  let userName = params.userName;
  let realName = params.realName;
  let fieldTitle = params.fieldTitle;
  let editMode = params.editMode;
  let isTrackRevisions = params.isTrackRevisions;

  let isDocChanged = false;

  let url;
  if (type == 'flow') {
    url = rootPath + '/flow/download?skey=' + token + '&flowId=' + flowId + '&attachId=' + attachId + '&t=' + Date.now();
  } else {
    url = rootPath + '/visual/download?skey=' + token + '&attachId=' + attachId + '&t=' + Date.now();
  }

  let isDebug = false;
  let callbackUrl = '';
  if (isDebug) {
    url = 'http://developer.xiaocaicloud.com/oa/public/images/demo.docx?token=' + token;
    callbackUrl = 'http://123.60.141.47:8088/oa/onlyoffice/callback?skey=' + token;
  } else {
    callbackUrl = rootPath + '/onlyoffice/callback?skey=' + token;
  }

  console.log('url', url);

  let documentType = 'word';
  if (ext == 'xls' || ext== 'xlsx') {
    documentType = 'cell';
  } else if (ext == 'ppt' || ext == 'pptx') {
    documentType = 'slide';
  } else if (ext == 'wps' || ext == 'wpt' || ext == 'pdf' || ext == 'htm' || ext == 'html') {
    documentType = 'word';
  }

  const config = {
    documentType: documentType,
    document: {
      title: fieldTitle,
      url: url,
      // 当前用户对于当前文档的操作权限
      permissions: {
        // 启用评论
        comment: false,
        // 启用下载
        download: true,
        // 启用编辑
        edit: true,
        // 启用导出
        print: true,
        // 启用预览
        review: true,
      },
      fileType: ext, //文件类型
      //文档标识符
      key: type + '_' + id + '_' + Date.now(),
    },
    editorConfig: {
      // 编辑器常规配置
      customization: {
        // 自动保存可以关闭，常规ctrl+s更好用
        autosave: false,
        forcesave: true,
        compactToolbar: true,
        forcesave: true,
        toolbarNoTabs: true,
        help: false,
        compactHeader: true,
        hideRightMenu: true,
        logo: {
          //自定义logo配置
          image: '/resource/img/logo.png',
          imageDark: '/resource/img/logo.png',
          url: '/resource/img/',
          visible: true,
        },
      },
      mode: mode == 'w' ? 'edit' : 'view', //view为只能浏览  edit为编辑
      // 回调
      callbackUrl: mode == 'w' ? callbackUrl:'', // 当浏览时，不能传callbackUrl否则会显示为空白
      // 菜单显示语言
      lang: 'zh-CN',
      // 当前操作用户信息
      user: {
        name: realName,
        id: userName,
      },
    },
    events: {
      onAppReady: function () {
        window.editor = this; // 保存编辑器实例
      },
      onRequestSaveAs: function (event) {
        // 处理另存为请求（手动保存时触发）
        console.log('保存数据:', event.data);
      },
      onDocumentStateChange: function (event) {
        console.log('onDocumentStateChange event', event);
        if (event.data) {
          // 文章有修改
          isDocChanged = true;
        } else {
          console.log('Changes are collected on document editing service');
        }
      },
    },
  };

  const script = document.createElement('script');
  script.src = onlyofficeServerUrl + 'web-apps/apps/api/documents/api.js';
  script.onload = () => {
    initDocEditor();
  };
  script.onerror = () => {
    console.error('Failed to load OnlyOffice DocsAPI script.');
  };
  document.head.appendChild(script);

  /**
   * 初始化编辑器
   */
  function initDocEditor() {
    // 在流程中保存草稿（xls格式）后刷新（此时window.docEditor不为空），但是编辑器中取的还是旧的内容，通过销毁编辑器的方式无效
    // 可能是因为网络原因，在文件还没有保存成功时，加载了编辑器，所以改为推迟加载编辑器
    // 但其实也不一定是网络原因，因为是在保存完的事件中回调进行草稿的保存的，要看Onlyoffice保存时的机制
    if (documentType=='cell' && window.docEditor) {
      //   console.log('Clear docEditor');
      //   const editorContainer = document.getElementById(fieldName + '_onlyoffice');
      //   if (editorContainer) {
      //     editorContainer.innerHTML = "";
      //   }

      //   // 移除事件监听器（如果有）
      //   if (window.docEditor.events) {
      //       window.docEditor.events.onSave = null;
      //   }

      //   // 删除全局引用
      //   delete window.docEditor;

      // 1秒后加载，仍存在上述问题，得3秒才能正常
      setTimeout(()=> {
        // 初始化配置
        window.docEditor = new DocsAPI.DocEditor(fieldName + '_onlyoffice', config);
        console.log('initDocEditor docEditor', docEditor);
        console.log('initDocEditor config', config);
      }, 3000);
    } else {
      window.docEditor = new DocsAPI.DocEditor(fieldName + '_onlyoffice', config);
      console.log('initDocEditor docEditor', docEditor);
      console.log('initDocEditor config', config);
    }
  }

  // 启用修订模式
  if (editMode == 1) {
    window.editor.setEditModeAsync('edit').then(function() {
        console.log('修订模式已启用');
    }).catch(function(error) {
        console.error('无法启用修订模式', error);
    });    
  }

  
  // 显示修订痕迹
  if (isTrackRevisions) {
    window.editor.setTrackRevisionsAsync(true).then(function() {
        console.log('修订痕迹已显示');
    }).catch(function(error) {
        console.error('无法显示修订痕迹', error);
    });    
  }


  let operate = 1;
  window.onmessage = function (event) {
    console.log('event', event);
    let data = JSON.parse(event.data);
    if (data.event == 'onRequestUsers' && mode == 'w') {
      let frm = o(formName).getElementsByTagName('iframe')[0];
      if (!frm) {
        console.warn('onmessage', '没有iframe');
        return false;
      } else if (frm.getAttribute('name') != 'frameEditor') {
        console.warn('onmessage', 'iframe不是Onlyoffice Editor');
        return false;
      }

      let frameDocument = frm.contentDocument;
      console.log('frameDocument', frameDocument);
      if (frameDocument) {
        console.log('toolbar-file', $(frameDocument).find("li[data-layout-name='toolbar-file']"));

        // 隐藏onlyoffice菜单“文件”，以免手动点击后，点“保存”按钮，会直接提交表单，并且会带来未知原因的其它问题
        $(frameDocument).find("li[data-layout-name='toolbar-file']").hide();
      } else {
        console.warn('没有contentDocument');
      }      
    }

    if (data.event == 'onDocumentStateChange' && data.data == false) {
      myMsg('文件保存成功');
      isDocChanged = false;
      if (operate == 1) {
        toolbarSubmit(null, false, true);
      } else if (op == 2) {
        handleReturnFlow(null, true);
      } else {
        saveDraft(null, true);
      }
    }
  };

  function handleOnlyofficeSave(formName, op = 1) {
    console.log('window.editor', window.editor);
    let frm = o(formName).getElementsByTagName('iframe')[0];
    if (!frm) {
      console.warn('handleOnlyofficeSave', formName + ' 中没有iframe');
      return false;
    } else if (frm.getAttribute('name') != 'frameEditor') {
      console.warn('handleOnlyofficeSave', formName + ' 中的iframe不是Onlyoffice Editor');
      return false;
    }

    operate = op; // 0保存草稿 1提交 2退回

    // 文章未修改，则直接提交
    if (!isDocChanged || mode == 'r') {
      if (op == 1) {
        toolbarSubmit(null, false, true);
      } else if (op == 2) {
        handleReturnFlow(null, true);
      } else {
        saveDraft(null, true);
      }
      return false;
    }

    console.log('window.editor', window.editor);

    let frameDocument = frm.contentDocument;
    console.log('frameDocument', frameDocument);
    if (frameDocument) {
      if (frameDocument.getElementById('fm-btn-save')) {
        frameDocument.getElementById('fm-btn-save').click();
      } else {
        // 先调出“文件”菜单，再点击菜单项“保存”
        frameDocument.getElementById('file').click();
        frameDocument.getElementById('fm-btn-save').click();
      }

      return true;
    } else {
      console.warn(formName + ' 中没有contentDocument');
      return false;
    }
  }
  
  window.handleOnlyofficeSave = handleOnlyofficeSave;
})();
